package com.ydy.utils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName: ParamsUtil
 * @Description:获得前端传参数的工具类
 * @author:
 * @date:
 */
public class ParamsUtil{


    private static Logger logger = LoggerFactory.getLogger(ParamsUtil.class);

    private static final String PAGE = "page"; //第几页

    private static final String PAGESIZE = "pageSize"; //每页条数

    private static final String SORT = "sort"; //排序字段

    private static final String ORDER = "order"; //排序方式

    private static final String PAGEMODEL = "pageModel"; //是否查询全部,不为空查询全部,不分页



    /**
     * 获取分页对象
     * @Title: getPageInfo
     * @author: yindy 2020/8/18 19:06
     * @param: [request]
     * @return: com.phjr.ddp.pojo.PageInfo
     * @throws
     */
    public static PageInfo getPageInfo(HttpServletRequest request){
        PageInfo page = new PageInfo();
        Assert.notNull(request, "Request must not be null");
        Enumeration paramNames = request.getParameterNames();
        while (paramNames != null && paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            String[] values = request.getParameterValues(paramName);
            if(StringUtils.isNotEmpty(values[0])) {
                if(page.equals(paramName)){
                    page.setPage(Integer.parseInt(values[0]));
                }else if(PAGESIZE.equals(paramName)){
                    page.setPageSize(Integer.parseInt(values[0]));
                }else if(SORT.equals(paramName)){
                    page.setSort(values[0]);
                }else if(ORDER.equals(paramName)){
                    page.setOrder(values[0]);
                }else if(PAGEMODEL.equals(paramName)){
                    page.setPagemodel(values[0]);
                }
            }
        }
        return page;
    }

    /**
     * 获取参数返回map
     * @Title: getParmsStarWith
     * @author: yindy 2020/8/18 17:35
     * @param: [request]
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @throws
     */
    public static Map<String, Object> getParams(HttpServletRequest request) {
        Assert.notNull(request, "Request must not be null");
        Enumeration paramNames = request.getParameterNames();
        Map<String, Object> params = new TreeMap<String, Object>();
        while (paramNames != null && paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            if(PAGE.equals(paramName) || PAGESIZE.equals(paramName)
                    || SORT.equals(paramName) || ORDER.equals(paramName) ){
                continue;
            }
            int index = -1;
            String[] values = request.getParameterValues(paramName);
            if(paramName.indexOf("[]") > index) { //特殊处理：参数名包含[]字符
                params.put(paramName.replace("[]",""), Arrays.asList(values));
            } else if(values.length > 1) {
                params.put(paramName, Arrays.asList(values));
            } else if(StringUtils.isNotEmpty(values[0])) { //字符串不为null或""
                params.put(paramName, values[0]);
            }
        }
        return params;
    }
    /**
     * 获得Bean参数
     * @Title: getBeanParam
     * @author: yindy 2020/8/18 18:30
     * @param: [t, request]
     * @return: T   bean对象
     * @throws
     */
    public static <T> T getBeanParam(T t, HttpServletRequest request) {
        try {
            Map<String, Object> map = getParams(request);
            Field[] fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String fieldName = field.getName();
                String type = field.getType().getName();
                List<Object> list = new ArrayList<>();
                // 获取具体值
                field.setAccessible(true);
                for(String key:map.keySet()){
                    String newKey = key;
                    if(key.contains("[")){
                        newKey = key.substring(0,key.indexOf("["));
                    }
                    if (fieldName.equals(newKey)) {
                        try {
                            String value = MapUtils.getString(map,key);
                            if("java.lang.Integer".equals(type)){
                                field.set(t,Integer.valueOf(value));
                            }else if("java.math.BigDecimal".equals(type)){
                                field.set(t,new BigDecimal(value));
                            }else if("java.util.Date".equals(type)){
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                field.set(t,sdf.parse(value));
                            }else if("java.util.List".equals(type)){
                                list.add(value);
                                field.set(t,list);
                            }else{
                                field.set(t,value);
                            }
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 获得异常信息
     * @Title: getErrorMsg
     * @author: yindy 2020/8/28 15:01
     * @param: [e]
     * @return: java.lang.String
     * @throws
     */
    public static String getErrorMsg(Exception e) {
        StringWriter stringWriter= new StringWriter();
        PrintWriter writer= new PrintWriter(stringWriter);
        e.printStackTrace(writer);
        StringBuffer buffer= stringWriter.getBuffer();
        return buffer.toString();
    }

}
